# encoding: utf-8
"""
complex.py

Created by Vivek Bhagwat on 2008-03-19.
Part of physicslibrary project on Google Code.
SVN: http://physicslibrary.googlecode.com/svn/trunk/

The absolute value of 3 + 4i is 5.0
"""

import sys
import os

class ComplexNumber(object):
	"""docstring for Complex Number"""
	def __init__(self, real, imaginary):
		self.real = real
		self.imaginary = imaginary
	
	def conjugate(self):
		"""docstring for conjugate"""
		return ComplexNumber(self.real, -1*self.imaginary)

	def absolute(self):
		return ((self.real ** 2) + (self.imaginary ** 2)) ** 0.5	
	
	def __str__(self):
		if self.imaginary >= 0:
			return '%f + %fi' % (self.real, self.imaginary)
		else:
			return '%d - %di' % (self.real, -1*self.imaginary)
	
	def square(self):
		return self.multiply(self)
	
	def add(self, other):
		return ComplexNumber(self.real + other.real, self.imaginary + other.imaginary)
	
	def subtract(self, other):
		return ComplexNumber(self.real - other.real, self.imaginary - other.imaginary)
	
	def multiply(self, other):
		return ComplexNumber(self.real*other.real + -1*self.imaginary*other.imaginary, \
		 self.real*other.imaginary + self.imaginary*other.real)
		
		
	def divide(self, other):
		denominator = other.real**2.0 + other.imaginary**2.0
		numReal = self.real*other.real*1.0 + self.imaginary*other.imaginary*1.0
		numImag = self.imaginary*other.real - self.real*other.imaginary
		return ComplexNumber(numReal/denominator, numImag/denominator)


	def sqrt(self):
		"""p is the square root of a + abs(self) all over root 2"""
		p = ((self.real + (self.absolute())**0.5)**0.5)/(2 ** 0.5)
		if p != 0:
			q = self.imaginary / 2.0 / p
			return ComplexNumber(p, q)
		else:
			return ComplexNumber(0, 0)
	
	
def main():
	c = ComplexNumber(2, 6)
	other = ComplexNumber(4, 1)
	print "The absolute value of", c, "is", c.absolute()
	print "The absolute value of", other, "is", other.absolute()
	print "The conjugate of", c, "is", c.conjugate()
	print "The square of", c, "is", c.square()
	print "The product of", c, "and", other, "is", c.multiply(other)
	print "The sum of", c, "and", other, "is", c.add(other)
	print "The difference of", c, "and", other, "is", c.subtract(other)
	print "The quotient of", c, "and", other, "is", c.divide(other)
	print "The product of", c, "and its conjugate", c.conjugate(), "is", \
	c.multiply(c.conjugate())	
	print "The square root of", c, "is", c.sqrt()

if __name__ == '__main__':
	main()

